﻿using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.FileProviders;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using YiSha.Basics;
using YiSha.Business.AutoJob;
using YiSha.Service;
using YiSha.SqlSugars;
using YiSha.Util;

namespace YiSha.Admin.Web
{
    /// <summary>
    /// 全局信息初始化（所有的初始化都放这里）
    /// </summary>
    public class GlobalInit
    {
        /// <summary>
        /// 初始化配置信息
        /// </summary>
        public static void Init(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region SqlSugar ORM配置
            //初始化Sugar类型
            SugarBase.DbType = ConvertDbType.GetDbType(GlobalContext.SystemConfig.DBProvider);
            //初始化Sugar数据库连接字符串
            SugarBase.DB_ConnectionString = GlobalContext.SystemConfig.DBConnectionString;
            #endregion
            #region Autofac全局引用 用于其他地方获取注入的实例信息
            AutofacUtil.Container = app.ApplicationServices.GetAutofacRoot();
            #endregion
            #region 静态文件读取配置
            string resource = Path.Combine(env.ContentRootPath, "Resource");
            //
            FileService.CreateDirectory(resource);

            app.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = GlobalContext.SetCacheControl
            });
            app.UseStaticFiles(new StaticFileOptions
            {
                RequestPath = "/Resource",
                FileProvider = new PhysicalFileProvider(resource),
                OnPrepareResponse = GlobalContext.SetCacheControl
            });
            #endregion
            //
            GlobalContext.ServiceProvider = app.ApplicationServices;
            //开启定时任务
            if (!GlobalContext.SystemConfig.Debug)
            {
                new JobCenter().Start(); // 定时任务
            }
        }
    }
}
